package com.briup.store.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
import com.briup.common.response.Result;
import com.briup.common.utils.UserContext;
import com.briup.store.config.AliPayConfig;
import com.briup.store.domain.dto.OrderItemInsertDTO;
import com.briup.store.domain.pojo.Order;
import com.briup.store.service.OrderService;
import com.briup.store.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;


    @GetMapping("/pay")
    public void pay(String orderId, Double totalPrice, String itemList, HttpServletResponse response){
        //配置阿里支付客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), aliPayConfig.getFormat(), aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());

        //创建支付宝交易页面请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //设置支付成功后支付宝回调地址
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + orderId + "\","
                + "\"total_amount\":\"" + totalPrice + "\","
                + "\"subject\":\"" + itemList + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //设置支付宝完成支付后跳转的本地页面
        request.setReturnUrl("http://localhost:8081/#/order");

        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
            response.setContentType("text/html;charset=" + aliPayConfig.getCharset());
            // 直接将完整的表单html输出到页面
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单未已支付
                Order order = new Order();
                //设置订单ID
                order.setId(tradeNo);
                //设置订单状态
                order.setStatus(2);
                //设置支付编号
                order.setTrackingNumber(alipayTradeNo);
                //设置支付方式
                order.setPayWay("支付宝沙箱环境支付");

                order.setDistributionMode("顺丰快递");

                //设置支付时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                order.setPayDate(LocalDateTime.parse(gmtPayment, formatter));

                orderService.updateOrderById(order);
            }
        }
        return "success";
    }


    /**
     * 余额支付
     * @param totalPrice 订单金额
     * @param id 订单ID
     * @return
     */
    @PostMapping("/balancePay")
    @Transactional
    public Result<Double> pay(String totalPrice,String id){
        System.out.println(UserContext.getUser());
        //查看当前登录用户余额
        BigDecimal balancePay = userService.getBalance(UserContext.getUser());
        BigDecimal totalPricePay = new BigDecimal(totalPrice);

        //判断余额是否充足
        if (balancePay.doubleValue() < totalPricePay.doubleValue()) {
            //余额不足提示充值
            throw new SystemException(CodeAndMessageEnum.INSUFFICIENT_BALANCE);
        }else {
            //余额充足，扣除余额
            BigDecimal newBalance = balancePay.subtract(totalPricePay);
            //修改用户余额
            userService.updateBalance(newBalance);
        }

        //修改订单状态
        // 更新订单未已支付
        Order order = new Order();
        //设置订单ID
        order.setId(id);
        //设置订单状态
        order.setStatus(2);
        //设置支付编号
        order.setTrackingNumber(UUID.randomUUID().toString());
        //设置支付方式
        order.setPayWay("余额支付");

        order.setDistributionMode("京东快递");

        //设置支付时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        order.setPayDate(LocalDateTime.now());

        //更新订单信息
        orderService.updateOrderById(order);

        //更新商品销量【暂不处理】: 后续可自行扩展
        // 先获取订单项中的商品id和数量，然后再逐个商品更新其销量

        return Result.success(balancePay.subtract(totalPricePay).doubleValue());
    }

}
